<?php

/**
 * 内容展示
 * Class MiContentShow
 */
class MiContentShowAction extends Action
{
    //平台id
    static protected $cid;

    /**
     * MiContentShow constructor.
     */
    public function __construct()
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return false;
        }

        self::$cid = Session::$user['customerId'];
    }

    /**
     * 获取内容展示列表接口
     * @param null $name /内容名称
     * @param null $startTime /开始时间
     * @param null $endTime /结束时间
     * @param int $start /分页起始
     * @param int $limit /分页大小
     * @param string $by /排序
     * @param string $order /排序规则
     * @return object
     */
    public function getContentShowList($name = null, $startTime = null, $endTime = null, $start = 0, $limit = 10,
                                       $by = 'updateTime', $order = 'desc')
    {


        $cid = self::$cid;
        Session::switchCustomer(0);
        $contentShow_table = M('micontent_show');
        Session::switchCustomer($cid);
        $where = [];
        if ($name) {
            $where['a.name'] = ['like', '%' . $name . '%'];
        }

        if ($startTime && $endTime) {
            $where['a.createTime'] = [['EGT', $startTime],['ELT', $endTime]];
        }

        $where['a.deleted'] = 0;
        $where['a.cid'] = $cid;
        $resultList = $contentShow_table->alias('a')
            ->join('wx_micontent_show_tag_list b on a.id = b.contentShowId and b.cid=' . $cid)
            ->join('wx_micontent_show_tag c on b.tagId = c.id and c.cid=' . $cid)
            ->join('wx_mishare d on a.id=d.moduleId and d.module="miContentShow"')
            ->field('a.id, a.name, a.createTime, GROUP_CONCAT(c.name) as tagNames,GROUP_CONCAT(c.id) AS tagIds,
            d.viewUv')
            ->where($where)
            ->limit($start, $limit)
            ->group('a.id')
            ->order('a.' . $by . ' ' . $order)
            ->select();
        //var_dump($contentShow_table->getLastSql());exit;
        if ($resultList == null) {
            Log::write('contentShow为空:' . $contentShow_table->getLastSql());
            Output::instance()->object([
                'total' => 0,
                'results' => []
            ]);
            return false;
        }

        $customer = WeixinApi::getCustomer();
        if ($customer['mode'] && $customer['grantStatus']) {
            $domainName = $customer["appid"];
            $http['RESOURCEURL'] = "http://" . $domainName . "." . C('NEWSERVER_NAME').'/';
        } else {
            $http['RESOURCEURL'] = C("SERVER_NAME").'/';
        }

        //生成预览
        foreach ($resultList as $key => $val) {
            /*http://newtest.mboxone.com/spa/index.html#/quan/infoList?customerId=50&params=%7B%22id%22%3A%2222%22%7D
*/
            $link = $http['RESOURCEURL'] . 'spa/index.html#/quan/infoList?customerId='.$cid.'&params=%7B%22id%22%3A%22' . $val['id'] . '%22%7D';
            $val['link'] = $link;
            $resultList[$key] = $val;
        }

        $total = $contentShow_table->alias('a')
            ->field('a.id')
            ->where($where)
            ->count();
        Output::instance()->object([
            'total' => $total,
            'results' => $resultList
        ]);
    }

    /**
     * 保存||更新内容展示
     * @param null $id /内容id
     * @param null $name /内容名称
     * @param $recommendList /推荐文章
     * @param null $contentTagList /关联的文章列表
     * @param null $tagList /关联的标签
     * @param null $joinQuanId /关联的圈子
     * @param null $joinQuanTip /圈子的提示文字
     * @param $shareTitle /分享标题
     * @param null $shareDescription /分享描述
     * @param $sharePic /分享图片
     * @param null $templateId /模板类型
     */
    public function saveContentShow($id = null, $name = null, $recommendList = null, $contentTagList = null, $tagList= null, $joinQuanId = null,
                                    $joinQuanTip = null, $shareTitle = null, $shareDescription = null, $sharePic =null,
                                    $templateId = null)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        $contentShow_table = M('micontent_show');
        $shareBase_table = M("mishare");
        $shareMater_table = M("mishare_material");
        $miContentRecommend_table = M("micontent_show_recommend");
        $relation_table = M("micontent_show_content");
        $tagRelation_table = M("micontent_show_tag_list");
        Session::switchCustomer($cid);
        $data = [];
        $massage = '';
        if(!$sharePic){
            $massage = '分享图片不能为空';
        }
        if(!$shareDescription){
            $massage = '分享描述不能为空';
        }
        if(!$shareTitle){
            $massage = '分享标题不能为空';
        }
        if(count(json_decode($contentTagList)) < 1){
            $massage = '分组展示菜单不能为空';
        }
        if(!$recommendList){
            $massage = '顶部轮播文章不能为空';
        }
        if (!$name) {
            $name = '新建内容展示';
        }

        if($massage){
            Output::instance()->object([
                'code' => -1,
                'msg' => $massage,
                'results' => []
            ]);
            return;
        }

        $flagId = $id;
        $data['cid'] = $cid;
        $data['name'] = $name;
        $data['joinQuanId'] = $joinQuanId;
        $data['joinQuanTip'] = $joinQuanTip;
        $data['shareTitle'] = $shareTitle;
        $data['shareDescription'] = $shareDescription;
        $data['sharePic'] = $sharePic;
        $data['templateId'] = $templateId;
        $data['createTime'] = date('Y-m-d H:i:s');
        $data['updateTime'] = date('Y-m-d H:i:s');

        $retId = 0;
        $bool = false;
        M()->startTrans();
        //保存内容展示表
        if (!$id) {
            $id = $contentShow_table->add($data);
            $retId = $id;
        } else {
            $bool = $contentShow_table->where('id = ' . $id)->save($data);
        }

        if (!$retId && $bool == false) {
            Log::write('内容展示表保存失败:'.$contentShow_table->getLastSql());
            M()->rollback();
            Output::instance()->object([
                'code' => -1,
                'msg' => '保存失败'
            ]);
            return;
        }

        $shareBaseData = [
            'module' => 'miContentShow',
            'moduleId' => $id,
            'cid' => $cid
        ];
        $shareMaterial = [
            'title' => $shareTitle,
            'shareImg' => $sharePic,
            'description' => $shareDescription,
        ];
        //保存||更新分享基础表分享素材表
        if ($flagId) {
            $shareBaseId = $shareBase_table->where($shareBaseData)->getField('id');
            if(!$shareBaseId){
                Log::write('分享基础表保存失败:'.$shareBase_table->getLastSql());
                M()->rollback();
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '数据存取失败',
                    'results' => []
                ]);
                return;
            }
            $shareMaterialRet = $shareMater_table->where('sId='.$shareBaseId)->save($shareMaterial);
        } else {
            $shareBaseData['createTime'] = date('Y-m-d H:i:s');
            $shareBaseId = $shareBase_table->add($shareBaseData);
            if(!$shareBaseId){
                Log::write('分享基础表保存失败:'.$shareBase_table->getLastSql());
                M()->rollback();
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '数据存取失败',
                    'results' => []
                ]);
                return;
            }
            $shareMaterial['sId'] = $shareBaseId;
            $shareMaterialRet = $shareMater_table->add($shareMaterial);
        }
        if(!is_numeric($shareMaterialRet)){
            Log::write('分享素材表保存失败:'.$shareMater_table->getLastSql());
            M()->rollback();
            Output::instance()->object([
                'code' => -1,
                'msg' => '数据存取失败',
                'results' => []
            ]);
            return;
        }

        //保存推荐文章及关联文章
        if($flagId){
            $recommendBool = $miContentRecommend_table->where(['contentShowId' => $id, 'cid' => $cid])->delete();
            $relationBool = $relation_table->where(['cid' => $cid, 'contentShowId' => $id])->delete();
            $tagRelation_table->where(['cid' => $cid, 'contentShowId' => $id])->delete();
            if(!$recommendBool || !$relationBool){
                Log::write('更新清除历史关联关系失败:'.M()->getDbError());
                M()->rollback();
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '数据存储失败',
                    'results' => []
                ]);
                return;
            }
        }

        $recommendIds = explode(',', $recommendList);
        $sql = 'insert into wx_micontent_show_recommend (`cid`,`contentShowId`,`contentId`,`createTime`) VALUES ';
        foreach ($recommendIds as $key => $val) {
            $sql .= "(" . $cid . "," . $id . "," . $val . ",'" . date('Y-m-d H:i:s') . "'),";
        }
        $sql = trim($sql, ',') . ';';
        $recommendRet = M()->execute($sql);
        if(!$recommendRet){
            Log::write('保存内容分享推荐文章失败'.M()->getLastSql());
            M()->rollback();
            Output::instance()->object([
                'code' => -1,
                'msg' => '数据存取失败',
                'results' => []
            ]);
            return;
        }


        $sql = 'insert into wx_micontent_show_content (`cid`,`contentShowId`,`contentTagId`,`contentTagAlias`,`createTime`) VALUES ';
        $contentTagList = json_decode($contentTagList, true);
        foreach ($contentTagList as $key => $val) {
            $sql .= "(" . $cid . "," . $id . "," . $val['tagId'] . ",'". $val['contentTagAlias'] ."','" . date('Y-m-d H:i:s') . "'),";
        }
        $sql = trim($sql, ',') . ';';
        $recommendRet = M()->execute($sql);
        if(!$recommendRet){
            Log::write('保存内容分享关联文章失败'.M()->getLastSql());
            M()->rollback();
            Output::instance()->object([
                'code' => -1,
                'msg' => '数据存取失败',
                'results' => []
            ]);
            return;
        }


        //保存关联的标签
        if($tagList){
            $tagList = explode(',', $tagList);
            $sql = 'insert into wx_micontent_show_tag_list (`cid`,`contentShowId`,`tagId`,`createTime`) VALUES ';
            foreach ($tagList as $key => $val) {
                $sql .= "(" . $cid . "," . $id . "," . $val . ",'" . date('Y-m-d H:i:s') . "'),";
            }
            $sql = trim($sql, ',') . ';';
            $recommendRet = M()->execute($sql);
            if(!$recommendRet){
                Log::write('保存内容分享关联标签失败'.M()->getLastSql());
                M()->rollback();
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '数据存取失败',
                    'results' => []
                ]);
                return;
            }
        }

        M()->commit();
        Output::instance()->object([
            'code' => 0,
            'msg' => '保存成功',
            'results' => [
                'id' => $id
            ]
        ]);
    }

    /**
     * 获取单篇内容展示详情
     * @param $id /内容展示id
     */
    public function getContentShowById($id)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        //内容展示表
        $contentShow_table = M('micontent_show');
        //推荐文章表
        $contentRecommend_tabel = M('micontent_show_recommend');
        //文章标签关联表
        $tagList_table = M('micontent_show_tag_list');
        $bothContent_table = M('micontent_show_content');
        //文章标签表
        $contentTagList_table = M('micontent_tag_list');
        //模板表
        $tplModel = M("pb_template");
        Session::switchCustomer($cid);

        $result = $contentShow_table->alias('a')
            ->join('left join wx_miyouquan b on a.joinQuanId = b.id and b.cId='.$cid)
            ->field('a.*,b.name as joinQuanName')
            ->where(['a.id' => $id, 'a.deleted' => 0])
            ->find();
        //var_dump($contentShow_table->getLastSql());exit;
        $result['tagList'] = $tagList_table->alias('a')
            ->field('c.id, c.name')
            ->join('wx_micontent_show_tag c on a.tagId = c.id and c.cid ='.$cid)
            ->where(['a.contentShowId' => $id, 'a.cid' => $cid])
            ->select();

        if($result == null){
            Log::write('查询内容展示详情失败:'.$contentShow_table->getLastSql());
            Output::instance()->object([
                'code' => -1,
                'msg' => '数据不存在',
                'results' => []
            ]);
            return;
        }

        $customer = WeixinApi::getCustomer();
        if ($customer['mode'] && $customer['grantStatus']) {
            $domainName = $customer["appid"];
            $http['RESOURCEURL'] = "http://" . $domainName . "." . C('NEWSERVER_HOST');
        } else {
            $http['RESOURCEURL'] = C("SERVER_HOST");
        }

        //获取推荐文章表
        $result['recommendList'] = $contentRecommend_tabel->alias('a')
            ->join('inner join wx_micontent b on a.contentId = b.id and b.deleted = 0')
            ->where(['cid' => $cid, 'contentShowId' => $result['id']])
            ->field('b.id, b.title, b.picUrl, b.createTime')
            ->order('b.createTime desc')
            ->select();

        foreach($result['recommendList'] as $key => $val){
            $val['link'] = $http['RESOURCEURL'] . 'call.html?customerId=' . $cid . '&module=micontent&method=getMiContentDetail&params=%7B%22id%22%3A%22' . $val['id'] . '%22%7D';
            $result['recommendList'][$key] = $val;
        }

        //获取关联的文章标签以及第一个标签对应的文章
        $result['contentTagArr'] = $bothContent_table->alias('a')
            ->join('inner join wx_micontent_tag b on a.contentTagId = b.id and b.fromCustomerId = '.$cid)
            ->where(['a.cid' => $cid, 'a.contentShowId' => $result['id']])
            ->field('a.contentTagId as id, a.contentTagAlias, b.tagName')
            ->select();
        $result['firstTagContents'] = [];

        $result['templateList'] = $tplModel->where(['module' => 'miContentShow'])->select();

        if($result['contentTagArr']){
            $result['firstTagContents'] = $contentTagList_table->alias('a')
                ->join('inner join wx_micontent b on a.webPageId = b.id and b.deleted = 0')
                ->where(['a.fromCustomerId' => $cid, 'a.tagId' => $result['contentTagArr'][0]['contentTagId']])
                ->field('a.tagId, b.id, b.title, b.picUrl, b.createTime')
                ->limit(0, 10)
                ->order('b.createTime desc')
                ->select();

            if($result['firstTagContents']){
                foreach($result['firstTagContents'] as $key=>$val){
                    $val['link'] = $http['RESOURCEURL'] . 'call.html?customerId=' . $cid . '&module=micontent&method=getMiContentDetail&params=%7B%22id%22%3A%22' . $val['id'] . '%22%7D';
                    $result['firstTagContents'][$key] = $val;
                }
            }
        }

        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'results' => $result
        ]);
    }

    /**
     * 删除内容展示
     * @param $id /内容展示id
     */
    public function delete($id)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        //内容展示表
        $contentShow_table = M('micontent_show');
        //分享基础表
        $shareBase_table = M("mishare");
        //分享素材表
        $shareMater_table = M("mishare_material");
        //推荐文章表
        $contentRecommend_tabel = M('micontent_show_recommend');
        //文章标签关联表
        $bothContent_table = M('micontent_show_content');
        //文章标签表
        $contentTagList_table = M('micontent_tag_list');
        Session::switchCustomer($cid);

        M()->startTrans();
        $contentShowRet = $contentShow_table->where('id ='.$id)->save([
            'deleted' => 1
        ]);
        $shareBaseId = $shareBase_table->where(['cid' => $cid, 'module' => 'miContentShow', 'moduleId' => $id])->getField('id');
        $shareBaseRet = $shareBase_table->where('id='.$shareBaseId)->save(['deleted' => 1]);
        $shareMaterialRet = $shareMater_table->where(['sId' => $shareBaseId])->delete();
        $recommendRet = $contentRecommend_tabel->where(['contentShowId' => $id, 'cid' => $cid])->delete();
        $bothTagRet = $bothContent_table->where(['cid' => $cid, 'contentShowId' => $id])->delete();

        if(!$contentShowRet || !$shareBaseRet || !$shareMaterialRet || !$recommendRet || !$bothTagRet){
            Log::write('删除内容展示失败:'.M()->getDbError());
            M()->rollback();
            Output::instance()->object([
                'code' => -1,
                'msg' => '删除失败',
                'results' => []
            ]);
            return;
        }

        M()->commit();
        Output::instance()->object([
            'code' => 0,
            'msg' => '删除成功',
            'results' => []
        ]);
    }

    /**
     * 获取推荐文章列表
     * @param null $title /文章标题
     * @param null $tagId /文章标签
     * @param int $start /分页起始
     * @param int $limit /分页大小
     * @param string $by /排序
     * @param string $order /排序
     * @return null || object
     */
    public function getContentList($title = null, $tagId = null, $start = 0, $limit = 10, $order = 'createTime',
                                   $by = 'desc')
    {
        $cid = self::$cid;
        Session::$user['customerId'];
        Session::switchCustomer(0);
        $micontent_table = M('micontent');
        Session::switchCustomer($cid);

        $where = [];
        if($title){
            $where['a.title'] = ['like', '%'.$title.'%'];
        }

        if($tagId){
            $where['b.tagId'] = $tagId;
        }
        $where['a.fromCustomerId'] = $cid;
        $where['a.deleted'] = 0;
        $where["a.type"]=array("EXP","=0 or a.type is null");
        $contentList = $micontent_table->alias('a')
            ->join('wx_micontent_tag_list b on a.id = b.webPageId and b.fromCustomerId='.$cid)
            ->field('a.id, a.title, a.updateTime, a.picUrl, a.description')
            ->where($where)
            ->limit($start, $limit)
            ->order('a.'.$order.' '.$by)
            ->group('a.id')
            ->select();
        //Log::write('1111:'.$micontent_table->getLastSql());
        if($contentList == null){
            Log::write('内容展示关联标签的内容不存在:'.$micontent_table->getLastSql());
            $massage = [
                'code' => 0,
                'msg' => '暂无文章',
                'total' => 0,
                'results' => []
            ];
            Output::instance()->object($massage);
            return;
        }

        $customer = WeixinApi::getCustomer();
        if ($customer['mode'] && $customer['grantStatus']) {
            $domainName = $customer["appid"];
            $http['RESOURCEURL'] = "http://" . $domainName . "." . C('NEWSERVER_HOST');
        } else {
            $http['RESOURCEURL'] = C("SERVER_HOST");
        }
        foreach($contentList as $key => $val){
            $val['link'] = $http['RESOURCEURL'] . 'call.html?customerId=' . $cid . '&module=micontent&method=getMiContentDetail&params=%7B%22id%22%3A%22' . $val['id'] . '%22%7D';
            $contentList[$key] = $val;
        }

        $total = $micontent_table->alias('a')
            ->where($where)
            ->count();
        //Log::write('2222:'.$micontent_table->getLastSql());
        $massage = [
            'code' => 0,
            'msg' => 'ok',
            'total' => $total,
            'results' => $contentList
        ];
        Output::instance()->object($massage);
    }

    /**
     * 获取内容展示的所有标签
     * @param null $tagName /标签名
     * @param int $start /分页起始
     * @param int $limit /分页大小
     * @param string $order /排序
     * @param string $by /排序
     * @param int $isAll /是否查询全部
     */
    public function GetTagList($tagName = null, $start = 0, $limit = 20, $order = 'createTime', $by = 'desc', $isAll = 0)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        $tag_table = M('micontent_show_tag');
        Session::switchCustomer($cid);
        $where = [];
        if($tagName){
            $where['name'] = $tagName;
        }
        $where['cid'] = $cid;
        $where['deleted'] = 0;
        if($isAll){
            $tagList = $tag_table->where($where)->field('id, name')->order($order.' '.$by)->select();
        }else{
            $tagList = $tag_table->where($where)->field('id, name')->limit($start, $limit)->order($order.' '.$by)->select();
        }

        if($tagList == null){
            Log::write('查询内容展示标签失败:'.$tag_table->getLastSql());
            Output::instance()->object([
                'code' => -1,
                'msg' => '暂无标签',
                'results' => []
            ]);
            return;
        }
        $total = $tag_table->where($where)->field('id')->count();
        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'total' => $total,
            'results' => $tagList
        ]);
    }

    /**
     * 新增内容展示标签
     * @param $tagName /标签名
     */
    public function addTag($tagName)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        $tag_table = M('micontent_show_tag');
        Session::switchCustomer($cid);

        $ret = $tag_table->add(['name' => $tagName, 'cid' => $cid, 'deleted' => 0, 'createTime' => date('Y-m-d H:i:s')]);
        if(!$ret){
            Log::write('保存内容展示标签失败:'.$tag_table->getLastSql());
            Output::instance()->object([
                'code' => -1,
                'msg' => '保存失败',
                'results' => []
            ]);
            return;
        }
        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'results' => [
                'id' => $ret
            ]
        ]);
    }

    /**
     * 删除内容展示标签
     * @param $id /标签id
     */
    public function delTag($id)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        $tag_table = M('micontent_show_tag');
        $contentShowTagList_table = M('micontent_show_tag_list');
        Session::switchCustomer($cid);
        M()->startTrans();
        $tagRet = $tag_table->where('id ='.$id)->save(['deleted' => 1]);
        $conShowTagRet = $contentShowTagList_table->where(['cid' => $cid, 'tagId' => $id])->delete();
        if(!$tagRet || !$conShowTagRet){
            Log::write('删除内容展示标签失败:'.M()->getDbError());
            M()->rollback();
            Output::instance()->object([
                'code' => -1,
                'msg' => '删除失败',
                'results' => []
            ]);
            return;
        }
        M()->commit();
        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'results' => []
        ]);
    }

    /**
     * 判断此标签是否和别的内容存在绑定
     * @param $id /标签id
     */
    public function beforeDelTag($id)
    {
        $cid = self::$cid;
        Session::switchCustomer(0);
        $contentShowTagList_table = M('micontent_show_tag_list');
        Session::switchCustomer($cid);
        $ret = $contentShowTagList_table->where(['cid' => $cid, 'tagId' => $id])->find();
        if($ret){
            Output::instance()->object([
                'code' => -1,
                'msg' => '存在正在使用的关联',
                'results' => []
            ]);
            return;
        }
        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'results' => []
        ]);
    }

    //获取素材标签模版列表

    public function miGetWebPageTagTemplateList($module = 'miContentShow'){

        $cid = self::$cid;
        Session::switchCustomer(0);
        $tplModel = M("pb_template");
        Session::switchCustomer($cid);
        $where['module'] = $module;
        $arr = $tplModel->where($where)->select();
        if ($arr) {
            Output::instance()->objArray($arr);
        } else {
            Output::instance()->resultCode();
        }
    }
}